'use strict';

const db = uniCloud.database()
const dbCmd = db.command

module.exports = {
  _before: function () {
    // 统一的前置拦截器，可以在此处做一些公共的权限验证等
  },

  /**
   * 获取裁判执裁记录列表
   */
  async getRefereeRecords(params = {}) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId
      const { page = 1, pageSize = 10, status, position } = params

      // 构建查询条件
      let whereCondition = {
        referee_id: userId
      }

      if (status) {
        whereCondition.record_status = status
      }
      
      // 添加职位筛选支持
      if (position) {
        whereCondition.position = position
      }

      // 查询执裁记录
      const collection = db.collection('match_referee_records')
      const countResult = await collection.where(whereCondition).count()
      
      const query = collection
        .where(whereCondition)
        .orderBy('match_date', 'desc') // 按比赛日期倒序，更符合用户习惯
        .skip((page - 1) * pageSize)
        .limit(pageSize)

      const result = await query.get()

      // 修改返回格式，与前端期望一致
      return {
        code: 0,
        message: '获取成功',
        data: {
          list: result.data, // 前端期望的是 list 字段
          total: countResult.total,
          page: page,
          pageSize: pageSize,
          totalPages: Math.ceil(countResult.total / pageSize)
        }
      }
    } catch (error) {
      console.error('获取执裁记录失败:', error)
      return {
        code: -2,
        message: '获取执裁记录失败: ' + error.message
      }
    }
  },

  /**
   * 获取裁判执裁统计数据（实时计算）
   */
  async getRefereeStatistics(params = {}) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId
      const { year = new Date().getFullYear() } = params

      // 实时查询执裁记录进行统计计算
      const collection = db.collection('match_referee_records')
      
      // 查询该年度已确认的执裁记录
      const startDate = new Date(year, 0, 1)
      const endDate = new Date(year + 1, 0, 1)
      
      const recordsResult = await collection.where({
        referee_id: userId,
        record_status: '已确认',
        match_date: dbCmd.gte(startDate).and(dbCmd.lt(endDate))
      }).get()

      const records = recordsResult.data || []

      // 计算统计数据
      let totalMatches = records.length
      let totalRatingSum = 0
      let ratingCount = 0
      let presentCount = 0

      records.forEach(record => {
        // 统计评分
        if (record.execution_rating && typeof record.execution_rating === 'number') {
          totalRatingSum += record.execution_rating
          ratingCount++
        }
        
        // 统计出勤（兼容多种出勤状态表示）
        const attendanceStatus = record.attendance_status
        if (attendanceStatus === 'present' || 
            attendanceStatus === '正常出勤' || 
            attendanceStatus === 'normal' ||
            !attendanceStatus) { // 默认为正常出勤
          presentCount++
        }
      })

      // 计算平均评分
      const averageRating = ratingCount > 0 ? Math.round(totalRatingSum / ratingCount * 10) / 10 : 0
      
      // 计算出勤率
      const attendanceRate = totalMatches > 0 ? Math.round((presentCount / totalMatches) * 100) : 100

      const statisticsData = {
            referee_id: userId,
            year: year,
        total_matches: totalMatches,
        average_rating: averageRating,
        attendance_rate: attendanceRate,
            last_update: new Date()
          }

      return {
        code: 0,
        message: '获取成功',
        data: statisticsData
      }
    } catch (error) {
      console.error('获取执裁统计失败:', error)
      return {
        code: -2,
        message: '获取执裁统计失败: ' + error.message
      }
    }
  },

  /**
   * 添加执裁记录
   */
  async addRefereeRecord(recordData) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId

      // 验证必填字段
      const requiredFields = ['match_id', 'referee_id', 'referee_name', 'position', 'match_title', 'match_level', 'match_date', 'match_venue', 'home_team', 'away_team']
      for (let field of requiredFields) {
        if (!recordData[field]) {
          return {
            code: -3,
            message: `缺少必填字段: ${field}`
          }
        }
      }

      // 准备记录数据
      const now = new Date()
      const newRecord = {
        ...recordData,
        attendance_status: recordData.attendance_status || '正常出勤',
        has_supervisor: recordData.has_supervisor || false,
        record_status: '草稿',
        create_time: now,
        update_time: now
      }

      // 插入记录
      const collection = db.collection('match_referee_records')
      const result = await collection.add(newRecord)

      // 如果有监督员，发送执裁记录创建通知给监督员
      if (recordData.has_supervisor && recordData.supervisor_id) {
        try {
          const notificationService = uniCloud.importObject('notification-service');
          
          await notificationService.sendNotification({
            userId: recordData.supervisor_id,
            type: 'referee_evaluation',
            title: '新的执裁记录待评价',
            content: `${recordData.referee_name}提交了新的执裁记录。比赛：${recordData.match_title}，执裁职位：${recordData.position}，对阵：${recordData.home_team} vs ${recordData.away_team}。请及时进行评价确认。`,
            relatedId: result.id,
            senderId: userId,
            extraData: {
              jump_type: 'record_detail',
              jump_url: `/packageMy/my/match-record-detail?id=${result.id}`,
              record_id: result.id,
              match_id: recordData.match_id,
              match_title: recordData.match_title,
              evaluation_type: 'pending',
              referee_id: recordData.referee_id,
              referee_name: recordData.referee_name
            }
          });
          
          // 通知已发送;
        } catch (notifyError) {
          console.error('发送执裁记录创建通知失败:', notifyError);
          // 不影响记录创建的主流程
        }
      }

      return {
        code: 0,
        message: '添加成功',
        data: {
          _id: result.id,
          ...newRecord
        }
      }
    } catch (error) {
      console.error('添加执裁记录失败:', error)
      return {
        code: -2,
        message: '添加执裁记录失败'
      }
    }
  },

  /**
   * 更新执裁记录
   */
  async updateRefereeRecord(recordId, updateData) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId

      // 查询记录是否存在且有权限修改
      const collection = db.collection('match_referee_records')
      const record = await collection.doc(recordId).get()

      if (!record.data || record.data.length === 0) {
        return {
          code: -3,
          message: '记录不存在'
        }
      }

      const recordData = record.data[0]
      
      // 权限检查：只有记录所有者可以修改草稿状态的记录
      if (recordData.referee_id !== userId) {
        return {
          code: -4,
          message: '无权限修改此记录'
        }
      }

      if (recordData.record_status === '已确认') {
        return {
          code: -5,
          message: '已确认的记录无法修改'
        }
      }

      // 更新记录
      const updateResult = await collection.doc(recordId).update({
        ...updateData,
        update_time: new Date()
      })

      return {
        code: 0,
        message: '更新成功',
        data: updateResult
      }
    } catch (error) {
      console.error('更新执裁记录失败:', error)
      return {
        code: -2,
        message: '更新执裁记录失败'
      }
    }
  },

  /**
   * 提交执裁记录（从草稿状态提交为待确认状态）
   */
  async submitRefereeRecord(recordId) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId

      // 查询记录
      const collection = db.collection('match_referee_records')
      const record = await collection.doc(recordId).get()

      if (!record.data || record.data.length === 0) {
        return {
          code: -3,
          message: '记录不存在'
        }
      }

      const recordData = record.data[0]

      // 权限检查：只有记录所有者可以提交
      if (recordData.referee_id !== userId) {
        return {
          code: -4,
          message: '无权限提交此记录'
        }
      }

      // 状态检查：只能提交草稿状态的记录
      if (recordData.record_status !== '草稿') {
        return {
          code: -5,
          message: '只能提交草稿状态的记录'
        }
      }

      // 验证必填字段是否完整
      const requiredFields = ['match_id', 'referee_name', 'position', 'match_title', 'match_level', 'match_date', 'match_venue', 'home_team', 'away_team']
      for (let field of requiredFields) {
        if (!recordData[field]) {
          return {
            code: -6,
            message: `请完善必填信息: ${field}`
          }
        }
      }

      // 更新记录状态为待确认
      await collection.doc(recordId).update({
        record_status: '待确认',
        update_time: new Date()
      })

      // 如果有监督员，发送执裁记录提交通知给监督员
      if (recordData.has_supervisor && recordData.supervisor_id) {
        try {
          const notificationService = uniCloud.importObject('notification-service');
          
          await notificationService.sendNotification({
            userId: recordData.supervisor_id,
            type: 'referee_evaluation',
            title: '执裁记录待您确认',
            content: `${recordData.referee_name}已提交执裁记录等待确认。比赛：${recordData.match_title}，执裁职位：${recordData.position}，对阵：${recordData.home_team} vs ${recordData.away_team}。请及时进行确认和评价。`,
            relatedId: recordId,
            senderId: userId,
            extraData: {
              jump_type: 'record_detail',
              jump_url: `/packageMy/my/match-record-detail?id=${recordId}`,
              record_id: recordId,
              match_id: recordData.match_id,
              match_title: recordData.match_title,
              evaluation_type: 'submitted',
              referee_id: recordData.referee_id,
              referee_name: recordData.referee_name
            }
          });
          
          // 通知已发送;
        } catch (notifyError) {
          console.error('发送执裁记录提交通知失败:', notifyError);
          // 不影响提交的主流程
        }
      }

      return {
        code: 0,
        message: '提交成功，等待确认'
      }
    } catch (error) {
      console.error('提交执裁记录失败:', error)
      return {
        code: -2,
        message: '提交执裁记录失败'
      }
    }
  },

  /**
   * 确认执裁记录
   */
  async confirmRefereeRecord(recordId, confirmData = {}) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId

      // 查询记录
      const collection = db.collection('match_referee_records')
      const record = await collection.doc(recordId).get()

      if (!record.data || record.data.length === 0) {
        return {
          code: -3,
          message: '记录不存在'
        }
      }

      const recordData = record.data[0]

      // 权限检查
      if (recordData.referee_id !== userId && recordData.supervisor_id !== userId) {
        return {
          code: -4,
          message: '无权限确认此记录'
        }
      }

      if (recordData.record_status === '已确认') {
        return {
          code: -5,
          message: '记录已确认'
        }
      }

      // 准备更新数据
      let updateFields = {
        record_status: '已确认',
        update_time: new Date()
      }

      // 如果是监督员确认，添加监督员的评价信息
      if (recordData.has_supervisor && recordData.supervisor_id === userId) {
        // 评分为可选项
        if (confirmData.execution_rating !== undefined && confirmData.execution_rating !== null && confirmData.execution_rating !== '') {
          updateFields.execution_rating = confirmData.execution_rating
        }
        if (confirmData.performance_evaluation) {
          updateFields.performance_evaluation = confirmData.performance_evaluation
        }
        if (confirmData.referee_fee !== undefined) {
          updateFields.referee_fee = confirmData.referee_fee
        }
      }

      // 更新记录状态
      await collection.doc(recordId).update(updateFields)

      // 发送执裁记录评价通知
      try {
        const notificationService = uniCloud.importObject('notification-service');
        
        // 判断是否是监督员评价
        const isSupervisorEvaluation = recordData.has_supervisor && recordData.supervisor_id === userId;
        
        if (isSupervisorEvaluation) {
          // 监督员评价通知
          let notificationContent = `您的执裁记录已收到监督员评价。比赛：${recordData.match_title}，执裁职位：${recordData.position}，对阵：${recordData.home_team} vs ${recordData.away_team}。`;
          
          // 添加评价详情
          if (confirmData.execution_rating) {
            notificationContent += `执行评分：${confirmData.execution_rating}分。`;
          }
          if (confirmData.performance_evaluation) {
            notificationContent += `表现评价：${confirmData.performance_evaluation}。`;
          }
          
          await notificationService.sendNotification({
            userId: recordData.referee_id,
            type: 'referee_evaluation',
            title: '监督员执裁评价',
            content: notificationContent,
            relatedId: recordId,
            senderId: userId,
            extraData: {
              jump_type: 'record_detail',
              jump_url: `/packageMy/my/match-record-detail?id=${recordId}`,
              record_id: recordId,
              match_id: recordData.match_id,
              match_title: recordData.match_title,
              evaluation_type: 'supervisor',
              execution_rating: confirmData.execution_rating,
              performance_evaluation: confirmData.performance_evaluation
            }
          });
          
          // 通知已发送
        } else {
          // 执裁记录确认通知（普通确认）
          await notificationService.sendNotification({
            userId: recordData.referee_id,
            type: 'referee_evaluation',
            title: '执裁记录已确认',
            content: `您的执裁记录已确认。比赛：${recordData.match_title}，执裁职位：${recordData.position}，对阵：${recordData.home_team} vs ${recordData.away_team}。`,
            relatedId: recordId,
            senderId: userId,
            extraData: {
              jump_type: 'record_detail',
              jump_url: `/packageMy/my/match-record-detail?id=${recordId}`,
              record_id: recordId,
              match_id: recordData.match_id,
              match_title: recordData.match_title,
              evaluation_type: 'confirmation'
            }
          });
          
          // 通知已发送
        }
      } catch (notifyError) {
        console.error('发送执裁记录评价通知失败:', notifyError);
        // 不影响确认的主流程
      }

      // 更新统计数据
      await this.updateStatistics(recordData.referee_id, recordData.match_date)

      return {
        code: 0,
        message: '确认成功'
      }
    } catch (error) {
      console.error('确认执裁记录失败:', error)
      return {
        code: -2,
        message: '确认执裁记录失败'
      }
    }
  },

  /**
   * 删除执裁记录
   */
  async deleteRefereeRecord(recordId) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId

      // 查询记录
      const collection = db.collection('match_referee_records')
      const record = await collection.doc(recordId).get()

      if (!record.data || record.data.length === 0) {
        return {
          code: -3,
          message: '记录不存在'
        }
      }

      const recordData = record.data[0]

      // 权限检查：只有记录所有者可以删除草稿状态的记录
      if (recordData.referee_id !== userId) {
        return {
          code: -4,
          message: '无权限删除此记录'
        }
      }

      if (recordData.record_status !== '草稿') {
        return {
          code: -5,
          message: '只能删除草稿状态的记录'
        }
      }

      // 删除记录
      await collection.doc(recordId).remove()

      return {
        code: 0,
        message: '删除成功'
      }
    } catch (error) {
      console.error('删除执裁记录失败:', error)
      return {
        code: -2,
        message: '删除执裁记录失败'
      }
    }
  },

  /**
   * 获取待确认记录
   */
  async getPendingRecords() {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId

      // 查询待确认的记录
      const collection = db.collection('match_referee_records')
      
      const result = await collection.where({
        $or: [
          // 裁判自己的待确认记录（所有自己的记录，无论是否有监督员）
          {
            referee_id: userId,
            record_status: '待确认'
          },
          // 监督员需要确认的记录
          {
            supervisor_id: userId,
            record_status: '待确认',
            has_supervisor: true
          }
        ]
      }).orderBy('create_time', 'desc').get()

      return {
        code: 0,
        message: '获取成功',
        data: result.data
      }
    } catch (error) {
      console.error('获取待确认记录失败:', error)
      return {
        code: -2,
        message: '获取待确认记录失败'
      }
    }
  },

  /**
   * 获取单条执裁记录详情
   * 权限控制：
   * - 待确认状态：有监督员的记录只有监督员能查看，无监督员的记录只有裁判员本人能查看
   * - 已确认状态：裁判员可以查看自己的记录，监督员可以查看自己确认过的记录
   */
  async getRecordDetail(recordId) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId

      if (!recordId) {
        return {
          code: -3,
          message: '记录ID不能为空'
        }
      }

      // 查询记录
      const collection = db.collection('match_referee_records')
      const result = await collection.doc(recordId).get()

      if (!result.data || result.data.length === 0) {
        return {
          code: -4,
          message: '记录不存在'
        }
      }

      const record = result.data[0]

      // 权限检查
      let hasPermission = false
      let permissionReason = ''

      if (record.record_status === '待确认') {
        // 待确认状态的权限逻辑
        if (record.has_supervisor && record.supervisor_id) {
          // 有监督员：只有监督员能查看和确认
          hasPermission = record.supervisor_id === userId
          permissionReason = hasPermission ? '监督员查看待确认记录' : '待确认记录只有监督员能查看'
        } else {
          // 无监督员：只有裁判员本人能查看和确认
          hasPermission = record.referee_id === userId
          permissionReason = hasPermission ? '裁判员查看自己的待确认记录' : '待确认记录只有裁判员本人能查看'
        }
      } else if (record.record_status === '已确认') {
        // 已确认状态的权限逻辑
        const isReferee = record.referee_id === userId
        const isSupervisorWhoConfirmed = record.supervisor_id === userId && record.has_supervisor
        
        hasPermission = isReferee || isSupervisorWhoConfirmed
        if (isReferee) {
          permissionReason = '裁判员查看自己的已确认记录'
        } else if (isSupervisorWhoConfirmed) {
          permissionReason = '监督员查看自己确认过的记录'
        } else {
          permissionReason = '已确认记录只有裁判员本人或确认的监督员能查看'
        }
      } else {
        // 其他状态（如草稿）：只有裁判员本人能查看
        hasPermission = record.referee_id === userId
        permissionReason = hasPermission ? '裁判员查看自己的记录' : '记录只有裁判员本人能查看'
      }

      if (!hasPermission) {
        return {
          code: -5,
          message: '无权限查看此记录'
        }
      }

      return {
        code: 0,
        message: '获取成功',
        data: record
      }
    } catch (error) {
      console.error('获取记录详情失败:', error)
      return {
        code: -2,
        message: '获取记录详情失败'
      }
    }
  },

  /**
   * 批量确认比赛记录 - 场次级别的确认
   */
  async confirmMatchRecords(evaluationData) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId
      
      // 验证必填字段
      if (!evaluationData.evaluations || !Array.isArray(evaluationData.evaluations)) {
        return {
          code: -3,
          message: '评价数据格式错误'
        }
      }

      const collection = db.collection('match_referee_records')
      const now = new Date()
      
      // 开始事务处理
      const transaction = await db.startTransaction()
      
      try {
        const updateResults = []
        
        // 批量更新每个裁判员的记录
        for (const evaluation of evaluationData.evaluations) {
          const { record_id, attendance_status, execution_rating, performance_evaluation, referee_fee } = evaluation
          
          if (!record_id) {
            throw new Error('记录ID不能为空')
          }
          
          // 先查询记录确认权限
          const recordResult = await collection.doc(record_id).get()
          if (!recordResult.data || recordResult.data.length === 0) {
            throw new Error(`记录 ${record_id} 不存在`)
          }
          
          const record = recordResult.data[0]
          
          // 权限检查
          if (record.has_supervisor && record.supervisor_id !== userId) {
            throw new Error(`无权确认记录 ${record_id}`)
          }
          
          if (!record.has_supervisor && record.referee_id !== userId) {
            throw new Error(`无权确认记录 ${record_id}`)
          }
          
          if (record.record_status !== '待确认') {
            throw new Error(`记录 ${record_id} 状态不正确，当前状态：${record.record_status}`)
          }
          
          // 准备更新数据
          const updateData = {
            record_status: '已确认',
            attendance_status: attendance_status || record.attendance_status,
            performance_evaluation: performance_evaluation || record.performance_evaluation,
            referee_fee: referee_fee || record.referee_fee,
            confirm_time: now,
            update_time: now
          }
          
          // 评分为可选项，只有提供了才更新
          if (execution_rating !== undefined && execution_rating !== null && execution_rating !== '') {
            updateData.execution_rating = execution_rating
          } else if (record.execution_rating) {
            updateData.execution_rating = record.execution_rating
          }
          
          // 如果是监督员确认，记录确认人信息
          if (record.has_supervisor && record.supervisor_id === userId) {
            updateData.confirmed_by = userId
            updateData.confirmed_by_name = verifyResult.data.userName || '监督员'
          }
          
          // 更新记录
          const updateResult = await collection.doc(record_id).update(updateData)
          updateResults.push({
            record_id: record_id,
            success: updateResult.updated > 0,
            referee_id: record.referee_id,
            match_date: record.match_date
          })
        }
        
        // 提交事务
        await transaction.commit()
        
        // 事务提交后，更新统计数据
        for (const result of updateResults) {
          if (result.success) {
            try {
              await this.updateStatistics(result.referee_id, result.match_date)
            } catch (statsError) {
              console.error('更新统计数据失败:', statsError)
              // 统计数据更新失败不影响主流程
            }
          }
        }
        
        // 发送通知给相关裁判员
        try {
          await this.sendConfirmationNotifications(evaluationData, userId)
        } catch (notifyError) {
          console.error('发送通知失败:', notifyError)
          // 通知失败不影响主流程
        }
        
        return {
          code: 0,
          message: '批量确认成功',
          data: {
            total: evaluationData.evaluations.length,
            success: updateResults.filter(r => r.success).length,
            results: updateResults
          }
        }
        
      } catch (transactionError) {
        // 回滚事务
        await transaction.rollback()
        throw transactionError
      }
      
    } catch (error) {
      console.error('批量确认记录失败:', error)
      return {
        code: -2,
        message: error.message || '批量确认记录失败'
      }
    }
  },
  
  /**
   * 发送确认通知给相关裁判员
   */
  async sendConfirmationNotifications(evaluationData, confirmerId) {
    try {
      const notificationService = uniCloud.importObject('notification-service')
      const collection = db.collection('match_referee_records')
      
      // 获取所有相关记录的详细信息
      const recordIds = evaluationData.evaluations.map(e => e.record_id)
      const recordsResult = await collection.where({
        _id: dbCmd.in(recordIds)
      }).get()
      
      const records = recordsResult.data
      
      // 按裁判员分组发送通知
      const refereeGroups = {}
      records.forEach(record => {
        if (!refereeGroups[record.referee_id]) {
          refereeGroups[record.referee_id] = []
        }
        refereeGroups[record.referee_id].push(record)
      })
      
      // 发送通知
      for (const refereeId in refereeGroups) {
        const refereeRecords = refereeGroups[refereeId]
        const matchTitles = refereeRecords.map(r => r.match_title).join('、')
        
        await notificationService.sendNotification({
          userId: refereeId,
          type: 'referee_evaluation',
          title: '执裁记录已确认',
          content: `您的执裁记录已确认：${matchTitles}`,
          relatedId: refereeRecords[0]._id,
          senderId: confirmerId,
          extraData: {
            jump_type: 'record_list',
            jump_url: '/packageMy/my/match-records',
            record_ids: refereeRecords.map(r => r._id),
            match_count: refereeRecords.length,
            evaluation_type: 'batch_confirmation'
          }
        })
      }
      
    } catch (error) {
      console.error('发送确认通知失败:', error)
      throw error
    }
  },

  /**
   * 更新统计数据
   */
  async updateStatistics(refereeId, matchDate) {
    try {
      const year = new Date(matchDate).getFullYear()
      const collection = db.collection('match_referee_statistics')
      const recordsCollection = db.collection('match_referee_records')

      // 查询该年度已确认的执裁记录
      const records = await recordsCollection.where({
        referee_id: refereeId,
        record_status: '已确认',
        match_date: dbCmd.gte(new Date(year, 0, 1)).and(dbCmd.lt(new Date(year + 1, 0, 1)))
      }).get()

      if (!records.data || records.data.length === 0) {
        return
      }

      // 计算统计数据
      const stats = {
        referee_id: refereeId,
        year: year,
        total_matches: records.data.length,
        main_referee_count: 0,
        assistant_referee_count: 0,
        fourth_official_count: 0,
        excellent_count: 0,
        good_count: 0,
        average_count: 0,
        poor_count: 0,
        total_fee: 0,
        attendance_rate: 0,
        last_update: new Date()
      }

      let normalAttendanceCount = 0

      records.data.forEach(record => {
        // 统计职位
        if (record.position === '主裁判') {
          stats.main_referee_count++
        } else if (record.position === '边裁判') {
          stats.assistant_referee_count++
        } else if (record.position === '第四官员') {
          stats.fourth_official_count++
        }

        // 统计评分
        if (record.execution_rating === '优秀') {
          stats.excellent_count++
        } else if (record.execution_rating === '良好') {
          stats.good_count++
        } else if (record.execution_rating === '一般') {
          stats.average_count++
        } else if (record.execution_rating === '较差') {
          stats.poor_count++
        }

        // 统计费用
        if (record.referee_fee) {
          stats.total_fee += record.referee_fee
        }

        // 统计出勤
        if (record.attendance_status === '正常出勤') {
          normalAttendanceCount++
        }
      })

      // 计算出勤率
      stats.attendance_rate = Math.round((normalAttendanceCount / stats.total_matches) * 100)

      // 更新或插入统计数据
      const existingStats = await collection.where({
        referee_id: refereeId,
        year: year
      }).get()

      if (existingStats.data && existingStats.data.length > 0) {
        // 更新现有统计
        await collection.doc(existingStats.data[0]._id).update(stats)
      } else {
        // 插入新统计
        await collection.add(stats)
      }

    } catch (error) {
      console.error('更新统计数据失败:', error)
    }
  },

  /**
   * 获取系列赛比赛视图数据（按比赛分组显示）
   */
  async getSeriesMatchView(params = {}) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId
      const { matchId } = params

      if (!matchId) {
        return {
          code: -3,
          message: '缺少系列赛ID参数'
        }
      }

      // 获取系列赛信息
      const matchCollection = db.collection('matches')
      const matchResult = await matchCollection.doc(matchId).get()
      
      if (!matchResult.data || matchResult.data.length === 0) {
        return {
          code: -4,
          message: '系列赛不存在'
        }
      }

      const matchData = matchResult.data[0]
      
      if (matchData.publisher_id !== userId) {
        return {
          code: -5,
          message: '无权限查看此系列赛的执裁记录'
        }
      }

      // 查询执裁记录 - 不使用skipPermission
      const collection = db.collection('match_referee_records')
      const result = await collection
        .where({
          match_id: matchId,
          record_status: '已确认'
        })
        .orderBy('match_date', 'asc')
        .get()

      // 处理执裁记录数据，按日期和比赛分组
      const matchSchedules = module.exports.groupRecordsByDate(result.data)

      // 统计待确认记录（虽然当前只查询已确认的，但为了完整性保留这个统计）
      const allRecordsResult = await collection
        .where({ match_id: matchId })
        .get()
      
      const allRecords = allRecordsResult.data || []
      const pendingRecords = allRecords.filter(r => r.record_status === '待确认').length

      return {
        code: 0,
        message: '获取成功',
        data: {
          seriesInfo: {
            title: matchData.title,
            level: matchData.level,
            location: matchData.location
          },
          matchSchedules: matchSchedules,
          totalRecords: allRecords.length,
          confirmedRecords: result.data.length,
          pendingRecords: pendingRecords
        }
      }
    } catch (error) {
      console.error('获取系列赛比赛视图失败:', error)
      return {
        code: -2,
        message: '获取系列赛比赛视图失败: ' + error.message
      }
    }
  },

  /**
   * 获取系列赛裁判员视图数据（按裁判员聚合）
   */
  async getSeriesRefereeView(params = {}) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId
      const { matchId, sortBy = 'totalMatches', sortOrder = 'desc' } = params

      if (!matchId) {
        return {
          code: -3,
          message: '缺少系列赛ID参数'
        }
      }

      // 验证用户权限
      const matchCollection = db.collection('matches')
      const matchResult = await matchCollection.doc(matchId).get()
      
      if (!matchResult.data || matchResult.data.length === 0) {
        return {
          code: -4,
          message: '系列赛不存在'
        }
      }

      const matchData = matchResult.data[0]
      if (matchData.publisher_id !== userId) {
        return {
          code: -5,
          message: '无权限查看此系列赛的执裁记录'
        }
      }

      // 查询所有执裁记录 - 只显示已确认的记录
      const collection = db.collection('match_referee_records')
      const result = await collection
        .where({ 
          match_id: matchId,
          record_status: '已确认'
        })
        .orderBy('match_date', 'asc')
        .get()

      // 使用现有的聚合方法处理数据
      let refereeStats = module.exports.aggregateRecordsByReferee(result.data)

      // 排序处理
      refereeStats.sort((a, b) => {
        if (sortBy === 'totalMatches') {
          return sortOrder === 'desc' ? b.totalMatches - a.totalMatches : a.totalMatches - b.totalMatches
        } else if (sortBy === 'averageRating') {
          const scoreA = module.exports.getRatingScore(a.averageRating)
          const scoreB = module.exports.getRatingScore(b.averageRating)
          return sortOrder === 'desc' ? scoreB - scoreA : scoreA - scoreB
        } else if (sortBy === 'refereeName') {
          return sortOrder === 'desc' ? b.refereeName.localeCompare(a.refereeName) : a.refereeName.localeCompare(b.refereeName)
        }
        return 0
      })

      // 计算整体平均评分
      const allRatings = result.data
        .filter(record => record.execution_rating)
        .map(record => record.execution_rating)
      const overallAverageRating = module.exports.calculateAverageRating(allRatings)

      return {
        code: 0,
        message: '获取成功',
        data: {
          seriesInfo: {
            title: matchData.title,
            level: matchData.level,
            location: matchData.location
          },
          refereeStats,
          totalReferees: refereeStats.length,
          totalRecords: result.data.length,
          averageRating: overallAverageRating
        }
      }
    } catch (error) {
      console.error('获取系列赛裁判员视图失败:', error)
      return {
        code: -2,
        message: '获取系列赛裁判员视图失败'
      }
    }
  },

  /**
   * 导出系列赛执裁记录Excel数据
   */
  async exportSeriesRecords(params = {}) {
    try {
      // 验证token
      const token = this.getUniIdToken()
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        }
      }

      const userService = uniCloud.importObject('user-service')
      const verifyResult = await userService.verifyToken({ token })
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        }
      }
      
      const userId = verifyResult.data.userId
      const { matchId, exportType = 'matches' } = params

      if (!matchId) {
        return {
          code: -3,
          message: '缺少系列赛ID参数'
        }
      }

      let exportData = []
      let fileName = ''

      if (exportType === 'matches') {
        // 导出比赛详情表
        const matchResult = await module.exports.getSeriesMatchView({ matchId })
        if (matchResult.code !== 0) {
          return matchResult
        }

        exportData = module.exports.formatMatchViewToExcel(matchResult.data.matchSchedules)
        fileName = `${matchResult.data.seriesInfo.title}_比赛执裁记录`
      } else if (exportType === 'referees') {
        // 导出裁判员统计表 - 直接查询避免重复token验证
        // 验证用户权限
        const matchCollection = db.collection('matches')
        const matchResult = await matchCollection.doc(matchId).get()
        
        if (!matchResult.data || matchResult.data.length === 0) {
          return {
            code: -4,
            message: '系列赛不存在'
          }
        }

        const matchData = matchResult.data[0]
        if (matchData.publisher_id !== userId) {
          return {
            code: -5,
            message: '无权限查看此系列赛的执裁记录'
          }
        }

        // 查询所有执裁记录 - 只显示已确认的记录
        const collection = db.collection('match_referee_records')
        const result = await collection
          .where({ 
            match_id: matchId,
            record_status: '已确认'
          })
          .orderBy('match_date', 'asc')
          .get()

        // 使用现有的聚合方法处理数据
        const refereeStats = module.exports.aggregateRecordsByReferee(result.data)

        exportData = module.exports.formatRefereeViewToExcel(refereeStats)
        fileName = `${matchData.title}_裁判员执裁统计`
      }

      return {
        code: 0,
        message: '导出数据生成成功',
        data: {
          exportData,
          fileName,
          exportTime: new Date().toISOString(),
          totalRecords: exportData.length
        }
      }
    } catch (error) {
      console.error('导出执裁记录失败:', error)
      return {
        code: -2,
        message: '导出执裁记录失败'
      }
    }
  },

  // 辅助方法
  groupRecordsByDate(records) {
    const dateMap = new Map()
    
    records.forEach(record => {
      const date = module.exports.formatDate(record.match_date)
      const weekday = module.exports.getWeekday(record.match_date)
      
      if (!dateMap.has(date)) {
        dateMap.set(date, {
          date,
          weekday,
          sessions: []
        })
      }
      
      const dayData = dateMap.get(date)
      
      // 查找是否已有相同时段的比赛
      let session = dayData.sessions.find(s => 
        s.homeTeam === record.home_team && 
        s.awayTeam === record.away_team &&
        module.exports.formatTime(record.match_date) === s.timeRange
      )
      
      if (!session) {
        session = {
          sessionId: `${date}_${record.home_team}_${record.away_team}`,
          timeRange: module.exports.formatTime(record.match_date),
          matchType: record.match_level || '比赛',
          homeTeam: record.home_team,
          awayTeam: record.away_team,
          venue: record.match_venue,
          referees: [],
          overallStatus: 'pending'
        }
        dayData.sessions.push(session)
      }
      
      // 岗位中英文转换
      const positionMap = {
        'main_referee': '主裁判',
        'assistant_referee': '助理裁判', 
        'fourth_official': '第四官员',
        'referee_supervisor': '裁判监督',
        '主裁判': '主裁判',
        '助理裁判': '助理裁判',
        '第四官员': '第四官员', 
        '裁判监督': '裁判监督'
      }
      
      // 评分数字转文字
      const getRatingText = (rating) => {
        if (typeof rating === 'number') {
          if (rating >= 90) return '优秀'
          if (rating >= 80) return '良好'
          if (rating >= 70) return '一般'
          if (rating >= 60) return '及格'
          return '较差'
        }
        return rating || '未评分'
      }
      
      // 考勤状态标准化
      const getAttendanceText = (attendance) => {
        const attendanceMap = {
          'present': '正常出勤',
          'late': '迟到',
          'early_leave': '早退',
          'absent': '缺勤',
          '正常出勤': '正常出勤',
          '迟到': '迟到',
          '早退': '早退',
          '缺勤': '缺勤'
        }
        return attendanceMap[attendance] || attendance || '未记录'
      }
      
      session.referees.push({
        refereeName: record.referee_name,
        position: positionMap[record.position] || record.position,
        rating: getRatingText(record.execution_rating),
        comment: record.supervisor_comment || record.performance_evaluation || '无评语',
        attendance: getAttendanceText(record.attendance_status),
        recordStatus: record.record_status
      })
      
      // 更新整体状态
      if (session.referees.every(r => r.recordStatus === '已确认')) {
        session.overallStatus = 'confirmed'
      } else if (session.referees.some(r => r.recordStatus === '待确认')) {
        session.overallStatus = 'pending'
      } else {
        session.overallStatus = 'draft'
      }
    })
    
    return Array.from(dateMap.values()).sort((a, b) => new Date(a.date) - new Date(b.date))
  },

  aggregateRecordsByReferee(records) {
    const refereeMap = new Map()
    
    // 岗位中英文转换映射（提前定义）
    const positionMap = {
      'main_referee': '主裁判',
      'assistant_referee': '助理裁判', 
      'fourth_official': '第四官员',
      'referee_supervisor': '裁判监督',
      '主裁判': '主裁判',
      '助理裁判': '助理裁判',
      '第四官员': '第四官员', 
      '裁判监督': '裁判监督'
    }
    
    // 评分数字转文字函数（提前定义）
    const getRatingText = (rating) => {
      if (typeof rating === 'number') {
        if (rating >= 90) return '优秀'
        if (rating >= 80) return '良好'
        if (rating >= 70) return '一般'
        if (rating >= 60) return '及格'
        return '较差'
      }
      return rating || '未评分'
    }
    
    records.forEach((record, index) => {
      if (!record.referee_id) {
        return
      }
      
      if (!refereeMap.has(record.referee_id)) {
        refereeMap.set(record.referee_id, {
          refereeId: record.referee_id,
          refereeName: record.referee_name,
          totalMatches: 0,
          positionStats: {},
          ratingStats: {},
          ratings: [],
          attendanceCount: 0,
          matchDetails: []
        })
      }
      
      const referee = refereeMap.get(record.referee_id)
      referee.totalMatches++
      
      // 获取中文岗位名称
      const positionCN = positionMap[record.position] || record.position
      
      // 统计职位（使用中文岗位名）
      if (!referee.positionStats[positionCN]) {
        referee.positionStats[positionCN] = 0
      }
      referee.positionStats[positionCN]++

      // 统计评分
      if (record.execution_rating) {
        const ratingText = getRatingText(record.execution_rating)
        referee.ratings.push(ratingText)
        if (!referee.ratingStats[ratingText]) {
          referee.ratingStats[ratingText] = 0
        }
        referee.ratingStats[ratingText]++
      }
      
      // 统计出勤
      if (record.attendance_status === '正常出勤') {
        referee.attendanceCount++
      }
      
      // 添加比赛详情
      referee.matchDetails.push({
        date: module.exports.formatDate(record.match_date),
        position: positionCN,
        matchInfo: `${record.home_team}vs${record.away_team}`,
        rating: record.execution_rating,
        recordStatus: record.record_status,
        venue: record.match_venue
      })
    })
    
    // 计算平均评分和出勤率
    const result = Array.from(refereeMap.values()).map(referee => ({
      ...referee,
      averageRating: module.exports.calculateAverageRating(referee.ratings),
      attendanceRate: referee.totalMatches > 0 ? Math.round((referee.attendanceCount / referee.totalMatches) * 100) : 0,
      matchDetails: referee.matchDetails.sort((a, b) => new Date(a.date) - new Date(b.date))
    }))
    
    return result
  },

  formatMatchViewToExcel(matchSchedules) {
    const exportData = []
    let index = 1
    
    matchSchedules.forEach(day => {
      day.sessions.forEach(session => {
        session.referees.forEach(referee => {
          exportData.push({
            序号: index++,
            比赛日期: day.date,
            时间段: session.timeRange,
            比赛类型: session.matchType,
            对阵双方: `${session.homeTeam} VS ${session.awayTeam}`,
            比赛场地: session.venue,
            裁判姓名: referee.refereeName,
            执裁职位: referee.position,
            出勤状态: referee.attendance,
            执裁评分: referee.rating || '未评分',
            监督员评语: referee.comment || '无',
            记录状态: referee.recordStatus
          })
        })
      })
    })
    
    return exportData
  },

  formatRefereeViewToExcel(refereeStats) {
    return refereeStats.map((referee, index) => ({
      序号: index + 1,
      裁判姓名: referee.refereeName,
      总执裁场次: referee.totalMatches,
      主裁判场次: referee.positionStats['主裁判'] || 0,
      边裁判场次: referee.positionStats['边裁判'] || 0,
      第四官员场次: referee.positionStats['第四官员'] || 0,
      优秀次数: referee.ratingStats['优秀'] || 0,
      良好次数: referee.ratingStats['良好'] || 0,
      一般次数: referee.ratingStats['一般'] || 0,
      较差次数: referee.ratingStats['较差'] || 0,
      平均评分: referee.averageRating || '无评分',
      出勤率: `${referee.attendanceRate}%`
    }))
  },

  calculateAverageRating(ratings) {
    if (ratings.length === 0) return null
    
    const ratingScores = {
      '优秀': 4,
      '良好': 3,
      '一般': 2,
      '较差': 1
    }
    
    const totalScore = ratings.reduce((sum, rating) => sum + (ratingScores[rating] || 0), 0)
    const averageScore = totalScore / ratings.length
    
    if (averageScore >= 3.5) return '优秀'
    if (averageScore >= 2.5) return '良好'
    if (averageScore >= 1.5) return '一般'
    return '较差'
  },

  getRatingScore(rating) {
    const scores = {
      '优秀': 4,
      '良好': 3,
      '一般': 2,
      '较差': 1,
      null: 0
    }
    return scores[rating] || 0
  },

  formatDate(date) {
    if (!date) return ''
    const d = new Date(date)
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
  },

  formatTime(date) {
    if (!date) return ''
    const d = new Date(date)
    return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
  },

  getWeekday(date) {
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    return weekdays[new Date(date).getDay()]
  },
} 